package com.honeybee.cloud.framework.oauth.controller;

import com.alibaba.fastjson.JSONObject;
import com.honeybee.cloud.framework.oauth.user.OauthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Objects;

/**
 * @Description 基础controller
 * @Author DELL
 * @Create 2019-02-13
 * @Since 1.0.0
 */
@SuppressWarnings("all")
public class BaseController {

    @Autowired
    protected HttpServletRequest httpServletRequest;
    @Autowired
    protected HttpServletResponse httpServletResponse;

    /**
     * 获取登录用户信息
     *
     * @return
     */
    protected OauthUser getCurrentUserInfo() {
        OAuth2Authentication auth2Authentication = (OAuth2Authentication) httpServletRequest.getUserPrincipal();
        if (Objects.isNull(auth2Authentication)) {
            return null;
        }
        Authentication authentication = auth2Authentication.getUserAuthentication();
        if (Objects.isNull(authentication)) {
            return null;
        }
        LinkedHashMap linkedHashMap = (LinkedHashMap) authentication.getDetails();
        if (Objects.isNull(linkedHashMap)) {
            return null;
        }
        Object o = linkedHashMap.get("principal");
        if (Objects.isNull(o)) {
            return null;
        }
        return JSONObject.parseObject(JSONObject.toJSONString(o), OauthUser.class);
    }

}
